%% 2. Startpoint Detection Code

clear; clc;

% PART 1: Load Skeletonized Vessel Image
[filename, pathname] = uigetfile('*', 'Select skeletonized vessel image'); 
if isequal(filename, 0)
    disp('User canceled the selection for: Skeletonized vessel image');
    return;
else
    vesselSkeleton = imread(fullfile(pathname, filename));
    if size(vesselSkeleton, 3) == 3
        vesselSkeleton = rgb2gray(vesselSkeleton); % Convert to grayscale if RGB
    end
    if ~islogical(vesselSkeleton)
        vesselSkeleton = imbinarize(vesselSkeleton); % Ensure it's binary
    end
    figure, imshow(vesselSkeleton), title('Skeletonized vessel image');
end

% PART 2: Extract Vessel Pixel Coordinates
[rowCoords, colCoords] = find(vesselSkeleton);
whitePixelCoordinates = [colCoords, rowCoords];
disp(['Total vessel pixels: ', num2str(size(whitePixelCoordinates, 1))]);

% PART 3: Load Optic Disc Coordinates
odFile = 'OD_coordinates.mat';
if isfile(odFile)
    load(odFile, 'odData');
    odX = odData.CenterX;
    odY = odData.CenterY;
    odRadius = odData.Radius;

    % Plot vessel pixels and OD
    figure, imshow(vesselSkeleton), title('Vessel Skeleton with OD Overlay');
    hold on;
    plot(whitePixelCoordinates(:, 1), whitePixelCoordinates(:, 2), 'g.', 'MarkerSize', 5);
    viscircles([odX, odY], odRadius, 'EdgeColor', 'r', 'LineWidth', 1);
    plot(odX, odY, 'ro', 'MarkerSize', 10, 'LineWidth', 2);
    hold off;
else
    disp('OD coordinates file not found.');
    return;
end

% PART 4: Identify Closest Points to OD
thresholdDistance = odRadius + 5;
distances = sqrt((whitePixelCoordinates(:, 1) - odX).^2 + (whitePixelCoordinates(:, 2) - odY).^2);
closestPoints = whitePixelCoordinates(distances > odRadius & distances <= thresholdDistance, :);

disp('Closest vessel points to the OD:');
disp(closestPoints);

% PART 5: Visualize Closest Points
figure, imshow(vesselSkeleton), title('Closest Vessel Points to OD');
hold on;
plot(whitePixelCoordinates(:, 1), whitePixelCoordinates(:, 2), 'g.', 'MarkerSize', 5);
viscircles([odX, odY], odRadius, 'EdgeColor', 'r', 'LineWidth', 1);
plot(odX, odY, 'ro', 'MarkerSize', 10, 'LineWidth', 2);
plot(closestPoints(:, 1), closestPoints(:, 2), 'bo', 'MarkerSize', 8, 'LineWidth', 1.5);
hold off;

% PART 6: Save Closest Points
save('Closest_Vessel_Points.mat', 'closestPoints');
disp('Closest vessel points saved.');
